package com.hzsai.utils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

/**
 * hzsai 2019/8/23
 * usage:
 **/
public class FileUtil {

    public static String exportDB(String dbName) {
        try {
            // 可以通过配置文件加载
            String username = "root";
            String password = "123456";

            String filename = "Export_file_" + DateUtil.getDate() + ".sql";

            // 将语句导出到临时文件夹里,
            // win下：C:\Users\_hzs_\AppData\Local\Temp\filename
            // linux下：/tmp/filename
            String exportFilepath = OSInfo.getTempPath() + filename;

            // windows linux分别处理
            String systemCMD = OSInfo.isWindows() ?
                    " cmd /c mysqldump " :
                    " /usr/bin/sh -c /usr/bin/mysqldump ";
            String commomCMD = " -u" + username + " -p" + password + " --databases " + dbName + "" +
                    " --default-character-set=utf8 --no-create-info --insert-ignore > " + exportFilepath;
            String cmd = systemCMD + commomCMD;

            System.out.println("CMD: " + cmd);

            Process process = Runtime.getRuntime().exec(cmd);

            // 同步等待结果完成
            if (process.waitFor() == 0) {
                return exportFilepath;
            }
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("导出出错!!!");
        } catch (InterruptedException e) {
            e.printStackTrace();
            System.out.println("返回处理错误!!!");
        }
        // 导出不成功返回Null
        return null;
    }

    public static String exportToClient(String filepath, HttpServletRequest req, HttpServletResponse rep) {
        try {

            // 选择保存路径是浏览器的功能，不是后端需要做的事

            String separate = OSInfo.isWindows() ?  "\\\\" : "/";
            String[] segs = filepath.split(separate);
            String filename = segs[segs.length-1];

            File file = new File(filepath);

            rep.reset();
            rep.setHeader("content-type", "application/octet-stream");
            rep.setContentType("application/octet-stream");
            rep.setHeader(
                    "Content-Disposition",
                    "attachment;filename=" + URLEncoder.encode(filename, "utf-8")
            );
            rep.setHeader("Content-Length", String.valueOf(file.length()));

            FileInputStream is = new FileInputStream(file);

            BufferedInputStream bis = new BufferedInputStream(is);
            OutputStream os = rep.getOutputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = bis.read(buffer)) != -1) {
                os.write(buffer, 0, len);
            }
            bis.close();
            os.close();
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
